#include <string.h>
#include <stdlib.h>
#include "lockerLoad.h"
#include "lockercompartmentLoad.h"
typedef int bool;
#define true 1
#define false 0

int loadLockers(char const *filename){
	FILE *ptr_file;
	ptr_file=fopen(filename,"r");
	if(!ptr_file){
		return 1;
	}
	int maxlinelen;
	int numlines=getFileInfo(ptr_file,&maxlinelen);
	lockercount=numlines;
	lockerdata=(struct LockerVars*) calloc(numlines,sizeof(struct LockerVars));
	char *buf=(char*) malloc(maxlinelen*sizeof(char));
	for(int i=0;i<numlines;i++){
		fgets(buf,maxlinelen,ptr_file);//load line into buffer;
		strcpy(lockerdata[i].lockerid,strtok(buf,"/"));//subsequent tokens...
		strcpy(lockerdata[i].city,strtok(NULL,"/"));//subsequent tokens...
		strcpy(lockerdata[i].province,strtok(NULL,"/"));//subsequent tokens...
		strcpy(lockerdata[i].location,strtok(NULL,"/"));//subsequent tokens...
		char *ph = strtok(NULL,"/");//get first token from buffer
		lockerdata[i].total=atoi(ph);
		ph = strtok(NULL,"/");
		lockerdata[i].used=atoi(ph);//get first token from buffer
	}
	fclose(ptr_file);
	return 0;
}

int writeLockers(char const *filename){
	FILE *ptr_file;
	ptr_file=fopen(filename,"w");
	if(!ptr_file){
		return 1;
	}
	for(int i=0;i<lockercount;i++){
		fprintf(ptr_file,"%s/%s/%s/%s/%d/%d\n",lockerdata[i].lockerid,lockerdata[i].city,lockerdata[i].province,lockerdata[i].location,lockerdata[i].total,lockerdata[i].used);
	}
	fclose(ptr_file);
	free(lockerdata);
	return 0;
}

void addLocker(struct LockerVars n){
	lockercount++;
	lockerdata=(struct LockerVars*) realloc(lockerdata,lockercount*sizeof(struct LockerVars));
	lockerdata[lockercount-1]=n;
}

void rmLocker(int index){
	for(int i=index;i<lockercount-1;i++){
		lockerdata[i]=lockerdata[i+1];
	}
	lockerdata=(struct LockerVars*) realloc(lockerdata,--lockercount*sizeof(struct LockerVars));
}


void readLocker()
{
    int i;
    for (i = 0; i < lockercount; i++)
    {
        printf("%s/%s/%s/%s/%d/%d\n\n",lockerdata[i].lockerid,lockerdata[i].city,lockerdata[i].province,lockerdata[i].location,lockerdata[i].total,lockerdata[i].used);
    }
}


int lockerAssignment(char* city){
    int cont = 1,index=0, answer,aux=1;
    printf("\nLockers disponibles:\n");
    for (int i = 0; i < lockercount; i++){
        if (strcmp(lockerdata[i].city, city) == 0 && lockerdata[i].total  - lockerdata[i].used != 0){
            printf("%d. %s\n", cont, lockerdata[i].lockerid);
            cont++;
        }
    }
	scanf("%d", &answer);
	cont=0;
	 for (int i = 0; i < lockercount && aux==1; i++){
        if (strcmp(lockerdata[i].city, city) == 0 && lockerdata[i].total  - lockerdata[i].used != 0){
            cont++;
			if(cont==answer){
			index=i;
			aux=0;
			}
        }
    }
	addUsed(index);
    return index;
}

void addUsed (int index){
	lockerdata[index].used = lockerdata[index].used+1;
	assignmentLocker(lockerdata[index].lockerid);
}

void removeUsed(int index){
	lockerdata[index].used=lockerdata[index].used-1;
}

void changeCity(char *locker){
	int aux=0;
	for (int i=0; i < lockercount; i++){
		if (strcmp(locker, lockerdata[i].lockerid)==0){
			aux=1;
			printf("Inserta la nueva localización del locker (ciudad): ");
			gets(lockerdata[i].city);
		}
	}
	if(aux==0){
		do{
			printf("\nEl locker introducido no existe. Introduce un id válido: ");
			gets(locker);
			for (int i=0; i < lockercount;i++){
				if (strcmp(locker, lockerdata[i].lockerid)==0){
					aux=1;
					printf("Inserta la nueva localización del locker (ciudad): ");
					gets(lockerdata[i].city);

				}
			}
		}while(aux==0);
	}
}

void deleteLocker(char *locker){
	int aux=0;
	for (int i=0; i < lockercount;i++){
		if (strcmp(locker, lockerdata[i].lockerid)==0){
			rmLocker(i);
			aux=1;
			deleteLockerCompartment(locker, lockerdata[i].total); //deletes from compartments file all the compartments of the locker
		}
	}
	if(aux==0){
		do{
			printf("\nEl locker introducido no existe. Introduce un id válido: ");
			gets(locker);
			for (int i=0; i < lockercount;i++){
				if (strcmp(locker, lockerdata[i].lockerid)==0){
				rmLocker(i);
				aux=1;
				deleteLockerCompartment(locker, lockerdata[i].total); //deletes all the compartments of the locker
			}
		}
		}while(aux==0);
	}
}

void newLockerID(){
	int aux=1;
	char substring[4],sublock[5];
	for (int i=0;i<4;i++){  //copy Lock
		sublock[i]=lockerdata[lockercount-2].lockerid[i];
	}
	strcpy(lockerdata[lockercount-1].lockerid,sublock);

	for (int i=4;i<8;i++){ //copy the number of the last locker 
		substring[i-4]=lockerdata[lockercount-2].lockerid[i];
	}

	int number=atoi(substring); //convert into an int the number
	number++;

	sprintf(substring,"%d", number); //convert into a string again to concatenate it later
	strcat(lockerdata[lockercount-1].lockerid, substring); 
	if (number/pow1(10,1)==0 && number/pow1(10,2)==0){ //if the number has one number
		lockerdata[lockercount-1].lockerid[6]=lockerdata[lockercount-1].lockerid[4];
		lockerdata[lockercount-1].lockerid[4]='0';
		lockerdata[lockercount-1].lockerid[5]='0';
	}

	if (number/pow1(10,1)!=0 && number/pow1(10,2)==0){
		lockerdata[lockercount-1].lockerid[6]=lockerdata[lockercount-1].lockerid[5];
		lockerdata[lockercount-1].lockerid[5]=lockerdata[lockercount-1].lockerid[4];
		lockerdata[lockercount-1].lockerid[4]='0';
	}
}

void newLocker(){
	addLocker(lockerdata[lockercount-1]);
	printf("\nDATOS DEL NUEVO LOCKER: ");
	newLockerID(); //calculates a new id adding 1 to the previous id
	printf("\nID: %s", lockerdata[lockercount-1].lockerid); //print the ID
	fflush(stdin);
	printf("\nCiudad: ");
	gets(lockerdata[lockercount-1].city);
	printf("\nProvincia: ");
	gets(lockerdata[lockercount-1].province);
	printf("\nUbicación: ");
	gets(lockerdata[lockercount-1].location);
	printf("\nNúmero de compartimentos: ");
	scanf("%d", &lockerdata[lockercount-1].total);
	lockerdata[lockercount-1].used=0;

	newCompartment(lockerdata[lockercount-1].lockerid,lockerdata[lockercount-1].total); //creates number of compartments of the locker in compartments' FILE
}




void menuLocker(){
	int option;
	char locker[10];
	bool bool=false;
	do{
		printf("\n*****ESCOGE UN NÚMERO*****\n");
		printf("\n1. Crear un nuevo locker.\n2. Eliminar un locker existente.\n3. Cambiar la ciudad de un locker existente.\n4. Listado de todos los lockers.\n5. Volver\n");
		fflush(stdin);
		scanf("%d", &option);
		while(option<1 && option>5){ //if the option is an invalid number
			system("clear");
			printf("\nEl número introducido no es correcto.");
			printf("\n*****ESCOGE UN NÚMERO*****\n");
			printf("\n1. Crear un nuevo locker.\n2. Eliminar un locker existente.\n3. Cambiar la ciudad de un locker existente.\n4. Listado de todos los lockers.\n5. Volver\n");
			fflush(stdin);
			scanf("%d", &option);
		}
	
		switch (option)
		{
		case 1: //creates a new locker
			system("clear");
			newLocker();
			break;
		case 2: //deletes a locker
			system("clear");
			printf("\nIntroduzca el id del locker que desea eliminar (ej:Lock001): ");
			fflush(stdin);
			gets(locker);
			deleteLocker(locker);
			printf("\nLocker eliminado correctamente.");
			break;
		case 3: //changes the city of a locker
			system("clear");
			printf("\nIntroduzca el id del locker que desea cambiar de ciudad(ej:Lock001): ");
			fflush(stdin);
			gets(locker);
			changeCity(locker);
			break;
		case 4:
			system("clear");
			readLocker();
			break;
		case 5:
			bool=true;
			break;
		}
			

	}while (bool==false);
}